package com.property.demo.controller;

import com.property.demo.dto.ApiResponse;
import com.property.demo.dto.ComplaintDTO;
import com.property.demo.model.Complaint;
import com.property.demo.service.ComplaintService;
import com.property.demo.util.DTOMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/api/complaints")
public class ComplaintController {

    @Autowired
    private ComplaintService complaintService;

    // 获取所有投诉（分页）
    @GetMapping
    public ResponseEntity<?> getAllComplaints(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long ownerId,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type) {
        
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
            
            Page<Complaint> complaintsPage;
            if (ownerId != null || (title != null && !title.isEmpty()) || 
                (status != null && !status.isEmpty()) || (type != null && !type.isEmpty())) {
                complaintsPage = complaintService.findByFilters(ownerId, title, status, type, pageable);
            } else {
                complaintsPage = complaintService.findAll(pageable);
            }
            
            List<ComplaintDTO> complaintDTOs = complaintsPage.getContent().stream()
                    .map(DTOMapper::toComplaintDTO)
                    .collect(Collectors.toList());
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", complaintDTOs);
            response.put("currentPage", complaintsPage.getNumber());
            response.put("totalItems", complaintsPage.getTotalElements());
            response.put("totalPages", complaintsPage.getTotalPages());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 获取所有投诉（不分页）
    @GetMapping("/all")
    public ResponseEntity<?> getAllComplaintsNoPage() {
        try {
            List<Complaint> complaints = complaintService.findAll();
            List<ComplaintDTO> complaintDTOs = DTOMapper.toComplaintDTOList(complaints);
            return ResponseEntity.ok(complaintDTOs);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 根据ID获取投诉
    @GetMapping("/{id}")
    public ResponseEntity<?> getComplaintById(@PathVariable Long id) {
        try {
            Optional<Complaint> complaint = complaintService.findById(id);
            if (complaint.isPresent()) {
                ComplaintDTO complaintDTO = DTOMapper.toComplaintDTO(complaint.get());
                return ResponseEntity.ok(complaintDTO);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 创建投诉
    @PostMapping
    public ResponseEntity<?> createComplaint(@RequestBody Complaint complaint) {
        try {
            Complaint savedComplaint = complaintService.save(complaint);
            ComplaintDTO complaintDTO = DTOMapper.toComplaintDTO(savedComplaint);
            return ResponseEntity.ok(new ApiResponse(true, "投诉创建成功", complaintDTO));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 更新投诉
    @PutMapping("/{id}")
    public ResponseEntity<?> updateComplaint(@PathVariable Long id, @RequestBody Complaint complaintDetails) {
        try {
            Complaint updatedComplaint = complaintService.update(id, complaintDetails);
            if (updatedComplaint != null) {
                ComplaintDTO complaintDTO = DTOMapper.toComplaintDTO(updatedComplaint);
                return ResponseEntity.ok(new ApiResponse(true, "投诉更新成功", complaintDTO));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 删除投诉
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteComplaint(@PathVariable Long id) {
        try {
            Optional<Complaint> complaint = complaintService.findById(id);
            if (complaint.isPresent()) {
                complaintService.delete(id);
                return ResponseEntity.ok(new ApiResponse(true, "投诉删除成功"));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
    
    // 批量删除投诉
    @DeleteMapping("/batch")
    public ResponseEntity<?> batchDeleteComplaints(@RequestBody List<Long> ids) {
        try {
            complaintService.deleteAll(ids);
            return ResponseEntity.ok(new ApiResponse(true, "投诉批量删除成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
    
    // 根据业主ID获取投诉
    @GetMapping("/owner/{ownerId}")
    public ResponseEntity<?> getComplaintsByOwner(@PathVariable Long ownerId) {
        try {
            List<Complaint> complaints = complaintService.findByOwnerId(ownerId);
            List<ComplaintDTO> complaintDTOs = DTOMapper.toComplaintDTOList(complaints);
            return ResponseEntity.ok(complaintDTOs);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
    
    // 根据状态或类型搜索投诉
    @GetMapping("/search")
    public ResponseEntity<?> searchComplaints(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type) {
        try {
            List<Complaint> complaints;
            if (status != null && !status.isEmpty()) {
                complaints = complaintService.findByStatus(status);
            } else if (type != null && !type.isEmpty()) {
                complaints = complaintService.findByType(type);
            } else {
                complaints = complaintService.findAll();
            }
            List<ComplaintDTO> complaintDTOs = DTOMapper.toComplaintDTOList(complaints);
            return ResponseEntity.ok(complaintDTOs);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
} 